//
//  ViewController.m
//  AVPlayerTest
//
//  Created by feng on 16/8/27.
//  Copyright © 2016年 冯宝东. All rights reserved.
//
#define fengURL @"http://www.fengbaodong.com/myVoice.mp3"
#define baoURL @"http://m2.music.126.net/zLk1RXSKMONJye6jB3mjSA==/1407374887680902.mp3"
#define   SW  [UIScreen mainScreen].bounds.size.width
#define SH   [UIScreen mainScreen].bounds.size.height


#define BDTry(A,B)		@try {\
A		} @catch (NSException *localException) {\
B   \}

#import "ViewController.h"
#import "PlayerMangerTool.h"
#import "VideoSwapTool.h"
#import "FBDDownloadManger.h"
#import "DBFilePathTool.h"
#import "AppDelegate.h"
#import "FBDUpload.h"
@interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate,NSURLSessionDelegate>
@property (nonatomic,strong)VideoSwapTool* videoTools;
@property(nonatomic,strong)PlayerMangerTool* playerMananger;
@property (nonatomic,strong)CALayer *preLayer;
//////////////////////////////////////////////////////////////////////////////////////////////
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, strong) NSData *resumeData;
@property (nonatomic, strong) NSURLSession *session;
@end

@implementation ViewController

 - ( void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

//    [self configeVideoSwap];
    
//    CADisplayLink *displayLink=[CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkWithTargetPRESSED:)];
//    displayLink.frameInterval=60;
//    
//    [displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    self.resumeData=nil;
    UIButton* SENDER=[UIButton buttonWithType:UIButtonTypeCustom];
    SENDER.frame=CGRectMake(100, 100, 200, 40);
    SENDER.backgroundColor=[UIColor blueColor];
    [SENDER setTitle:@"下载" forState:UIControlStateNormal];
    [SENDER addTarget:self action:@selector(download:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:SENDER];
    
     UIButton* upload=[UIButton buttonWithType:UIButtonTypeCustom];
     upload.frame=CGRectMake(100, 260, 200, 40);
     upload.backgroundColor=[UIColor blueColor];
     [upload setTitle:@"上传" forState:UIControlStateNormal];
     [upload addTarget:self action:@selector(uploadPressed:) forControlEvents:UIControlEventTouchUpInside];
     [self.view addSubview:upload];
   
//    char *str="1 wo is feng我要在上海工作了！";
//    char *str2="2 中间追加信息：我要在上海工作了！";
//    char *str3="3 最后追加信息：我要在上海工作了！";
//    NSData *data=[NSData dataWithBytes:str length:strlen(str)+1];
//    
//    
//    
//    NSData *data2=[NSData dataWithBytes:str2 length:strlen(str2)+1];//用于追加到可变G的mdata的中间对象
//    NSMutableData *mdata=[NSMutableData dataWithBytes:str3 length:strlen(str3)+1];
//    
//    [mdata appendData:data2];//追加data对象
//    
//    [mdata appendBytes:str length:strlen(str)+1];//2.追加字符串
//    NSLog(@"可变的字节对象:%@",mdata);
//    
//    [[DBFilePathTool defaultTools] createFileWithData:mdata withName:@"我的简历.txt"];
//    //NSLog(@"不可变的data的长度是:%ld,输出指针:%s",[data length],[data bytes]);//length是字节的长度,bytes是返回一个指针
//    
//    NS_DURING
//
//    NSArray *BB=@[@"12"];
//    [BB objectAtIndex:10];
//    NS_HANDLER
//    
//    NSLog(@"catry");
//    
//    NS_ENDHANDLER
//    
//    fengbaodongTestFunction();
//    
//    UncaughtExceptionHandler(nil);
    
}

-(void)YY
{
    if (self.task == nil) { // 开始（继续）下载
        if (self.resumeData) { // 恢复
            [self resume];
        } else { // 开始
            [self start];
        }
    } else { // 停止
        [self pause];
    }
}
- (void)download:(UIButton *)sender {
    // 按钮状态取反
   // sender.selected = !sender.isSelected;
    
    static int i=0;
    
    if(i%2==0)
    {
        [[FBDDownloadManger defaultTool] beginDownLoadMArrayURL:[NSMutableArray arrayWithArray:@[@"http://cache2.medsci.cn/video/up/2016-09/fc51b7dba4ff7070e86446181abae954.mp4",@"http://fengbaodong.com/myVoice.mp3"]]];
        
        
        [[FBDDownloadManger defaultTool]fbdDownloadMangerConfigeAllCurrentDownloadBlock:^(NSString *url, float progress) {
            NSLog(@"%@ ---------%.2f",url,progress);
        }];
        
        
    }else
    {
    
        
        [[FBDDownloadManger defaultTool]cacelAllLoadingMArrayURL];
        
    }
    
   
    i++;
    
    
    
    
}
-(void)uploadPressed:(UIButton *)sender
{
    NSString*imagePath=[[NSBundle mainBundle]pathForResource:@"1234" ofType:@".png"];
    
    FBDUpload* fileUpload=[[FBDUpload alloc] initWithUploadFilePath:imagePath withMIME:@"image/png" remotePath:nil];
    
    
    

}

//懒加载
-(NSURLSession *)session
{
    if (!_session) {
        // 获得session
        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
        self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

-(void)resume
{

    // 传入上次暂停下载返回的数据，就可以恢复下载
    self.task = [self.session downloadTaskWithResumeData:self.resumeData];
    
    // 开始任务
    [self.task resume];
    
    // 清空
    self.resumeData = nil;
    
}
-(void)start
{
    NSURL *url = [NSURL URLWithString:@"http://cache2.medsci.cn/video/up/2016-09/fc51b7dba4ff7070e86446181abae954.mp4"];
    self.task= [self.session downloadTaskWithURL:url];
    [self.task resume];
    
}
-(void)pause
{
    __weak typeof(self) vc = self;
    [self.task cancelByProducingResumeData:^(NSData *resumeData) {
        //  resumeData : 包含了继续下载的开始位置\下载的url
        vc.resumeData = resumeData;
        vc.task = nil;
    }];

}



#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // response.suggestedFilename ： 建议使用的文件名，一般跟服务器端的文件名一致
    NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    
    // 将临时文件剪切或者复制Caches文件夹
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    // AtPath : 剪切前的文件路径
    // ToPath : 剪切后的文件路径
    [mgr moveItemAtPath:location.path toPath:file error:nil];
}


- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
       didWriteData:(int64_t)bytesWritten
  totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    NSLog(@"获得下载进度--%@", [NSThread currentThread]);
    // 获得下载进度
    CGFloat progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
    NSLog(@"download progress is %.2f",progress);
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
    
    
}

/* If an application has received an
 * -application:handleEventsForBackgroundURLSession:completionHandler:
 * message, the session delegate will receive this message to indicate
 * that all messages previously enqueued for this session have been
 * delivered.  At this time it is safe to invoke the previously stored
 * completion handler, or to begin any internal updates that will
 * result in invoking the completion handler.
 */
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
{


}








-(void)displayLinkWithTargetPRESSED:(id)SENDER
{
    NSLog(@"%s",__func__);

}


#pragma mark -----------扫描条形码 --------------
-(void)configeVideoSwap
{


    self.preLayer=[[CALayer alloc]init];
    self.preLayer.bounds=[UIScreen mainScreen].bounds;
    self.preLayer.position=CGPointMake(SW/2.0, SH/2.0);
    self.preLayer.backgroundColor=[UIColor brownColor].CGColor;
    [self.view.layer addSublayer:self.preLayer];
    
    _videoSession=[[AVCaptureSession alloc] init];
    _videoDevice=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError* error=nil;
    _inputDevice=[AVCaptureDeviceInput deviceInputWithDevice:_videoDevice error:&error];
    if (error)
    {
        NSLog(@"初始化一个输入设备时出错 ，错误信息是：%@",error.localizedDescription);
        return;
    }
    
    if ([_videoSession canAddInput:_inputDevice])
    {
        [_videoSession addInput:_inputDevice];
    }
    
    _outDevice=[[AVCaptureVideoDataOutput  alloc] init];
    if ([_videoSession canAddOutput:_outDevice])
    {
        [_videoSession  addOutput:_outDevice];
    }
    
    
    self.output = [[AVCaptureMetadataOutput alloc] init];
//    self.output.rectOfInterest=CGRectMake(0, 0, SW, 150);
    
    [_videoSession addOutput:self.output];
    [self.output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

    //add preview layer
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_videoSession];
    self.previewLayer.frame =[UIScreen mainScreen].bounds;
    
    self.previewLayer.position =CGPointMake(CGRectGetMidX(self.previewLayer.frame), CGRectGetMidY(self.previewLayer.bounds));
    self.previewLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;
    [self.preLayer addSublayer:self.previewLayer];
    
    
    
    CGRect  intertRect=[self.previewLayer metadataOutputRectOfInterestForRect:CGRectMake(0, 0, SW, 150)];
    CGRect layerRect = [self.previewLayer rectForMetadataOutputRectOfInterest:intertRect];
    
    NSLog(@"%@,  %@",NSStringFromCGRect(intertRect),NSStringFromCGRect(layerRect));
    
    _output.rectOfInterest = intertRect;
    
  

    
    //start
    [_videoSession startRunning];


    CALayer* centerBlackLayer=[[CALayer alloc] init];
    centerBlackLayer.bounds=CGRectMake(0, 0, SW, 150);
    centerBlackLayer.position=CGPointMake(SW/2.0, 75);
    centerBlackLayer.backgroundColor=[UIColor blackColor].CGColor;
    centerBlackLayer.opacity=0.5;
    [self.previewLayer addSublayer:centerBlackLayer];
    
    
    


}







#pragma mark ----------- 音乐播放器--------------
-(void)configeMusicPlayer
{

    self.playerMananger=[[PlayerMangerTool alloc] init];
    NSString * mp3Path=   [[NSBundle mainBundle] pathForResource:@"123" ofType:@".mp3"];
    NSLog(@">>>>>>>>>>Mp3  Path: %@",mp3Path);
    [self.playerMananger    configeWithNewPlayerItemWithNetWorkURL:fengURL];
    
    
    
    //    [_playerMananger play];
    
    UIButton* nextSong=[UIButton buttonWithType:UIButtonTypeCustom];
    nextSong.bounds=CGRectMake(0, 0, 100, 40);
    nextSong.center=self.view.center;
    nextSong.backgroundColor=[UIColor brownColor];
    [nextSong  setTitle:@"下一首" forState:UIControlStateNormal];
    
    
    UIButton* controlSong=[UIButton buttonWithType:UIButtonTypeCustom];
    controlSong.bounds=CGRectMake(0, 0, 100, 40);
    controlSong.center=CGPointMake(40, 50);
    controlSong.backgroundColor=[UIColor brownColor];
    [controlSong  setTitle:@"暂停/播放" forState:UIControlStateNormal];
    
    [self.view addSubview:nextSong];
    [self.view addSubview:controlSong];
    [nextSong addTarget:self action:@selector(nextSongPressed) forControlEvents:UIControlEventTouchUpInside];
    [controlSong     addTarget:self action:@selector(controlSongPressed) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
    

}



-(void)nextSongPressed
{

    [self.playerMananger configeWithNewPlayerItemWithNetWorkURL:baoURL];


}
-(void)controlSongPressed
{

    _playerMananger.playerStatus=!_playerMananger.playerStatus;
    


}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{

    NSLog(@">>>>>>>>>>>>>>>>metadataObjects >>>%@",metadataObjects);




}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
